package com.tim.app.ui.fragment.friend;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrClassicFrameLayout;
import com.application.library.widget.refresh.PtrDefaultHandler;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.server.result.UserFollowResult;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.ui.adapter.friend.UserAdapter;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 关注的人页面
 */
public class ConcernedFragment extends BaseFragment implements View.OnClickListener, PtrHandler, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener {

    public static final String TAG = "ConcernedFragment";
    private View rootView;

    private PtrClassicFrameLayout refresh_layout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvUsers;
    private EmptyLayout emptyLayout;
    private UserAdapter adapter;
    private List<UserFollowResult.Res.Data.FollowUser> dataList;

    private User user;

    private int totalCount;

    public static ConcernedFragment newInstance(User user) {
        ConcernedFragment fragment = new ConcernedFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("user", user);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {

            rootView = inflater.inflate(R.layout.fragment_user, container, false);
            refresh_layout = (PtrClassicFrameLayout) rootView.findViewById(R.id.refresh_layout);
            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvUsers = (WrapRecyclerView) rootView.findViewById(R.id.wrvFriend);

            wrvUsers.setOverScrollMode(View.OVER_SCROLL_NEVER);
            refresh_layout.disableWhenHorizontalMove(true);
            refresh_layout.setPtrHandler(this);
            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            emptyLayout = new EmptyLayout(getActivity(), refresh_layout);
            emptyLayout.setEmptyButtonShow(false);
            emptyLayout.showLoading();
            emptyLayout.setEmptyDrawable(R.drawable.ic_empty_friend);

            if (dataList == null) {
                dataList = new ArrayList<>();
            }
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvUsers.setLayoutManager(layoutManager);

            user = (User) getArguments().getSerializable("user");

            if (UserManager.ins().isLogin() && null != user && !TextUtils.isEmpty(user.getUserId()) && user.getUserId().equals(UserManager.ins().getUserId())) {
                adapter = new UserAdapter(getActivity(), dataList, AppKey.TYPE_FOLLOW, true);
            } else {
                adapter = new UserAdapter(getActivity(), dataList, AppKey.TYPE_FOLLOW, false);
            }
            adapter.setOnItemClickListener(this);
            wrvUsers.setAdapter(adapter);
            if (UserManager.ins().isLogin() && UserManager.ins().getUserId().equals(user.getUserId())) {
                emptyLayout.setEmptyText("你还没有关注任何人", "");
            } else {
                String emptyText = "";
                if (null != user && user.getSex() == 1) {
                    emptyText = "他还没有关注任何人";
                } else {
                    emptyText = "她还没有关注任何人";
                }
                emptyLayout.setEmptyText(emptyText, "");
            }

        }
        EventManager.ins().registListener(EventTag.ON_USER_CANCEL_FOLLOW, eventListener);
        EventManager.ins().registListener(EventTag.ON_USER_FOLLOW, eventListener);
        initData();
        return rootView;
    }

    int pageNum = 1;

    /**
     * 获取关注用户列表
     */
    private void initData() {
        API_User.ins().getFollowUser(TAG, user.getUserId(), pageNum, AppKey.PAGE_SIZE, refreshCallback);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            refresh_layout.refreshComplete();
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                UserFollowResult result = new Gson().fromJson(resultValue, UserFollowResult.class);
                dataList.clear();
                totalCount = result.getTotal();
                EventManager.ins().sendEvent(EventTag.ON_FOLLOW_TITLT_LOAD_COMPLETED, 0, 0, totalCount);
                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        pageNum = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNum == result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, false);
                        } else {
                            load_more.loadMoreFinish(false, true);
                        }
                    }

                    if (dataList.size() == 0) {
                        emptyLayout.showEmpty();
                    } else {
                        emptyLayout.showContent();
                    }
                } else {
                    emptyLayout.showEmpty();
                }
            } else {
                emptyLayout.showEmptyOrError(errCode);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                UserFollowResult result = new Gson().fromJson(resultValue, UserFollowResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                        pageNum = result.getRes().getArraylist().getCurrentPageNo();
                        if (pageNum == result.getRes().getArraylist().getTotalPageCount()) {
                            load_more.loadMoreFinish(false, false);
                        } else {
                            load_more.loadMoreFinish(false, true);
                        }
                    }
                }
            } else {
                ToastUtil.showToast(errMsg);
            }

            return false;
        }
    };


    public int getFollowCount() {
        return totalCount;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        UserFollowResult.Res.Data.FollowUser data = dataList.get(position);
        SomeoneHomepageActivity.start(getActivity(), data.getUserMsg(), false);
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ON_USER_CANCEL_FOLLOW:
                    int type = arg1;
                    UserFollowResult.Res.Data.FollowUser user = (UserFollowResult.Res.Data.FollowUser) dataobj;
                    if (type == AppKey.TYPE_FRIEND || AppKey.TYPE_FANS == type) {
                        updateFriendType(user, true);
                    } else {
                        updateFriendType(user, false);
                    }
                    break;
                case EventTag.ON_USER_FOLLOW:
                    UserFollowResult.Res.Data.FollowUser value = (UserFollowResult.Res.Data.FollowUser) dataobj;
                    addFriend(value);
                    break;
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.ON_USER_CANCEL_FOLLOW, eventListener);
        EventManager.ins().removeListener(EventTag.ON_USER_FOLLOW, eventListener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    /**
     * 更新好友关系
     *
     * @param user
     */
    private void updateFriendType(UserFollowResult.Res.Data.FollowUser user, boolean isDelete) {
        for (int i = 0; i < dataList.size(); i++) {
            UserFollowResult.Res.Data.FollowUser currentUser = dataList.get(i);
            if (currentUser.getUserMsg().getUserId().equals(user.getUserMsg().getUserId())) {
                if (isDelete) {
                    dataList.remove(i);
                    adapter.notifyDataSetChanged();
                    if (dataList.size() == 0) {
                        emptyLayout.showEmpty();
                    }
                } else {
                    dataList.set(i, user);
                    adapter.notifyItemChanged(i);
                }
                break;
            }
        }
    }

    /**
     * 添加好友列表
     *
     * @param user
     */
    private void addFriend(UserFollowResult.Res.Data.FollowUser user) {
        boolean isHas = false;
        for (int i = 0; i < dataList.size(); i++) {
            UserFollowResult.Res.Data.FollowUser currentUser = dataList.get(i);
            if (currentUser.getUserMsg().getUserId().equals(user.getUserMsg().getUserId())) {
                dataList.set(i, user);
                adapter.notifyItemChanged(i);
                isHas = true;
                break;
            }
        }
        if (!isHas) {
            dataList.add(user);
            adapter.notifyDataSetChanged();
            emptyLayout.showContent();
        }
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, wrvUsers, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        initData();
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_User.ins().getFollowUser(TAG, user.getUserId(), pageNum + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
